package com.heima.user.service.impl;

import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath; // 私钥路径

    @Value("${leadnews.jwt.expire}")
    private Integer expire; // 过期时间

    @Override
    public ResponseResult login(LoginDto loginDto) {

        // 判断用户还是游客
        if (StringUtils.isNoneEmpty(loginDto.getPhone()) && StringUtils.isNoneEmpty(loginDto.getPassword())){
            // 用户登录

            // 查询用户是否存在
            ApUser loginUser = apUserMapper.findByDto(loginDto);
            System.err.println("loginUser = " + loginUser);
            if (loginUser == null){
//                throw new RuntimeException("用户不存在");
//                throw new LeadNewsException(404,"用户不存在");
                throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            // 判断密码是否正确
            if (!BCrypt.checkpw(loginDto.getPassword(),loginUser.getPassword())){
//                throw new RuntimeException("密码错误");
//                throw new LeadNewsException(500,"密码错误");
                throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            try {
                // 获取私钥文件
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);

                // 生成token
                // 去掉敏感数据
                loginUser.setPassword(null);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user",loginUser);

                // 返回信息给前端
                return ResponseResult.okResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("加载私钥失败");
            }

        }else {
            // 游客登录
            try {
                // 获取私钥文件
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);

                // 生成token
                // 去掉敏感数据
//                loginUser.setPassword(null);
                ApUser user =new ApUser();
                user.setId(0); // 0 代表游客
                String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, expire);

                Map<String,Object> map = new HashMap<>();
                map.put("token",token);

                // 返回信息给前端
                return ResponseResult.okResult(map);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("加载私钥失败");
            }
        }
    }
}
